// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
	* index action
	* @return {Promise} []
	*/
  async infolistAction() {
    const poptype = this.get('poptype');
    const keywords = this.get('keywords');
    // 根据类型调用相关接口
    if (poptype == 'guest') {
      this.getguest(keywords);
    }
    const data = {
      'name': 12,
      'value': 33
    };
    return this.json(data);
  }

  async subjectlistAction() {
    const slist = await this.model('or_subject')
      .alias('os')
      .field('os.id,os.name,os.remarks,os.usetime,ot.name as tname')
      .join(think.config('db.prefix') + 'or_subjecttype ot on os.t_id=ot.id')
      .where({'os.o_id': this.shop_userinfo.o_id})
      .select();

    const relist = {
      'draw': '',
      'data': slist,
      'breadcrumb': ''
    };

    return this.json(relist);
  }

  // 获取店家项目列表
  async getshopsubjectsAction() {
    const slist = await this.model('or_shop_subject')
      .alias('s')
      .field('s.id,s.price,s.subjectid,s.usetime, os.name, os.remarks')
      .join('think_or_subject os on os.id = s.subjectid')
      .where({'s.departmentid': this.shop_userinfo.departmentid})
      .select();
    const relist = {
      'draw': '',
      'data': slist,
      'breadcrumb': ''
    };
    return this.json(relist);
  }

  // 获取店家拉取的卡项列表
  async getshopcardsAction() {
    const num = this.post('num');
    const lim = this.post('lim');
    const sea = this.post('sea');

    // 获取新的卡项
    const data = await this.model('or_shop_card')
      .where({shopid: this.shop_userinfo.departmentid, isdisabled: 0, 'name|remarks|price|number': ['LIKE', '%' + sea + '%']})
      .page(num, lim)
      .countSelect();
    return this.json(data);
  }

  // 获取当前店家的产品列表
  async getshopgoodsAction() {
    const glist = await this.model('or_shop_goods')
      .alias('sg')
      .field('sg.id, sg.price, sg.goodsid, g.name, g.remarks')
      .join('think_or_goods g on g.id = sg.goodsid')
      .where({'sg.departmentid': this.shop_userinfo.departmentid, 'sg.isdisable': 0})
      .select();
    const relist = {
      'draw': '',
      'data': glist,
      'breadcrumb': ''
    };
    return this.json(relist);
  }

  // 获取商品列表
  async getgoodslistAction() {
    const filter = JSON.parse(this.post('filter'));

    const where = {
      'sg.isdisable': filter.isdisabled,
      'sg.shopid': this.shop_userinfo.departmentid
    };

    if (Number(filter.brandid)) where['g.brandid'] = filter.brandid;
    if (filter.keywords) where['g.name|g.number'] = ['like', '%' + filter.keywords + '%'];

    const list = await this.model('or_shop_goods')
      .alias('sg')
      .field('g.id, sg.price, sg.nums, g.name, g.remarks, g.brandid, g.number')
      .join('think_or_goods g on g.id = sg.goodsid')
      .where(where)
      .page(filter.currentpage, filter.pagesize)
      .countSelect();

    return this.json(list);
  }

  // 获取品牌列表接口
  async getbrandlistAction() {
    /* let did = await this.model('or_department').where({id: this.shop_userinfo.departmentid}).getField('pid', true)
		let list = await this.model('or_brand').where({isdisabled: 0, departmentid: did}).select() */
    const shopid = this.shop_userinfo.departmentid;
    const data = await this.model('or_shop_goods')
      .alias('sg')
      .field('b.*')
      .join('`think_or_goods` g on g.id=sg.goodsid')
      .join('`think_or_brand` b on b.id=g.brandid')
      .where({'sg.shopid': shopid})
      .select();

    const list = [];
    const idlen = [];
    data.forEach((res) => {
      if (idlen.indexOf(res.id) === -1) {
        idlen.push(res.id);
        list.push(res);
      }
    });
    return this.json(list);
  }

  // 获取当前店家产品和项目列表
  async getpinxiangAction() {
    const shopid = this.shop_userinfo.departmentid;

    const products = await this.model().query('select sg.*,g.name,g.remarks,g.brandid,g.categoryid,"false" as isuse from `think_or_shop_goods` sg left join `think_or_goods` g on g.id=sg.goodsid where sg.shopid=' + shopid + ' and sg.isdisable=0');

    const projects = await this.model().query('select ss.*,s.name,s.remarks,s.brandid,s.categoryid,"false" as isuse from `think_or_shop_subject` ss left join `think_or_subject` s on s.id=ss.subjectid where ss.shopid=' + shopid + ' and ss.isdisable=0');

    const data = {
      goods: products,
      subjs: projects
    };
    return this.json(data);
  }

  // 获取客户列表api
  async getguestlistAction() {
    const filter = this.post();
    const where = {
      'g.isdisable': 0,
      'g.name|g.username|g.vipcard': ['like', '%' + filter.search + '%'],
      'g.departmentid': this.shop_userinfo.departmentid,
      'g.initial_info': 1
    };
    const data = await this.model('or_guest')
      .alias('g')
      .field('g.*, v.vipname, v.goodsdiscount, v.subjectdiscount')
      .join('left join `think_or_guest_vipgrade` v on g.level = v.id')
      .where(where)
      .page(filter.currentpage, filter.pagesize)
      .order('g.id DESC')
      .countSelect();
    return this.json(data);
  }

  // 获取跨店客户信息
  async getDepartmentGuestListAction() {
    const filter = this.get();
    const departmentid = await this.model('or_department').where({id: this.shop_userinfo.departmentid}).getField('pid', true);
    const shopList = await this.model('or_department').where({pid: departmentid, floor: 1, isdisable: 0}).getField('id');
    const where = {
      'g.isdisable': 0,
      'g.name|g.username|g.vipcard': ['like', '%' + filter.search + '%'],
      'g.departmentid': ['IN', shopList],
      'g.initial_info': 1
    };
    const data = await this.model('or_guest')
      .alias('g')
      .field('g.*, d.name as shopname, v.vipname, v.goodsdiscount, v.subjectdiscount')
      .join('left join `think_or_guest_vipgrade` v on g.level = v.id')
      .join('left join `think_or_department` d on g.departmentid = d.id')
      .where(where)
      .page(filter.currentpage, filter.pagesize)
      .order('g.id DESC')
      .countSelect();
    return this.json(data);
  }

  // 获取项目分类列表
  async getsubjectcategorylistAction() {
    /* let did = await this.model('or_department').where({id: this.shop_userinfo.departmentid}).getField('pid', true)
		let list = await this.model('or_subjectcategory').where({departmentid: did, isdisable: 0}).select() */
    const shopid = this.shop_userinfo.departmentid;
    const data = await this.model('or_shop_subject')
      .alias('s')
      .field('sc.*')
      .join('`think_or_subject` ss on ss.id = s.subjectid')
      .join('think_or_subjectcategory sc on sc.id=ss.categoryid')
      .where({shopid: shopid})
      .select();
    const list = [];
    const idlen = [];
    data.forEach((res) => {
      if (idlen.indexOf(res.id) === -1) {
        idlen.push(res.id);
        list.push(res);
      }
    });
    return this.json(list);
  }

  // 获取店家项目列表
  async getsubjectlistAction() {
    const page = this.post();
    const pages = page.pages;
    const limits = page.limits;
    const search = page.search;
    const cid = page.cid;
    const shopid = this.shop_userinfo.departmentid;

    const where = {
      's.isdisable': 0,
      's.shopid': shopid
    };

    if (search != '') where['o.name|o.number'] = ['like', '%' + search + '%'];
    if (cid * 1 != 0) where['o.categoryid'] = cid;

    const list = await this.model('or_shop_subject')
      .alias('s')
      .field('o.id, s.price, s.usetime, o.name, o.remarks, o.brandid, o.number')
      .join('`think_or_subject` o on s.subjectid = o.id')
      .where(where)
      .page(pages, limits)
      .countSelect();

    return this.json(list);
  }

  // 获取客户的卡列表
  async getguestcardlistAction() {
    const id = this.get('guestid');
    const shopid = this.shop_userinfo.departmentid;
    const list = await this.model('or_shop_card').where({shopid: shopid}).select();
    return this.json(list);
  }

  // 获取客户的卡项列表
  async getguestcardsubjectlistAction() {
    const filter = JSON.parse(this.post('filter'));
    const nowtime = Math.round(Date.parse(new Date()) / 1000); // 当前时间
    // 先按照次数和剩余天数判断是否到期
    let where = 'gs.guestid = ' + filter.guestid;
    where += ' and gs.isdisabled = 0';
    // 期卡到期时间 nowtime > addtime+validity*86400 and cardtypeid = 1 次卡到期：nownum > 0 and cardtypeid = 2
    where += ' and ((' + nowtime + ' < gs.endtime and gs.cardtype = 1) or (gs.nownum > 0 and gs.cardtype = 2))';
    if (filter.keywords) where += ' and (s.name like "%' + filter.keywords + '%" or s.number like "%' + filter.keywords + '%")';
    if (filter.cardid && filter.cardid != 0) where += ' and gs.cardid = ' + filter.cardid;

    // 重新获取数据
    const subjectlist = await this.model('or_shop_guestcardsubject')
      .alias('gs')
      .field('gs.*, s.name, s.brandid, c.name as cardname, cs.xhprice')
      .join('left join `think_or_subject` s on gs.subjectid = s.id')
      .join('left join `think_or_shop_card` c on gs.cardid = c. id')
      .join('left join `think_or_shop_cardsubject` cs on gs.cardid = cs.cardid and gs.subjectid = cs.subjectid')
      .where(where)
      .page(filter.currentpage, filter.pagesize)
      .countSelect();

    return this.json(subjectlist);
  }
  // 获取客户暂存商品
  async getgueststoreAction() {
    const filter = JSON.parse(this.post('filter'));
    const where = {
      'tr.guestid': filter.guestid,
      'tr.nownum': ['>', 0],
      'tr.isdisabled': 0
    };
    if (filter.keywords) where['g.name|g.number'] = ['like', '%' + filter.keywords + '%'];
    // 获取客户暂存的项目和产品
    const list = await this.model('or_shop_guest_temp_reserve')
      .alias('tr')
      .field('tr.*, g.name')
      .join('left join `think_or_goods` g on tr.goodsid = g.id')
      .where(where)
      .page(filter.currentpage, filter.pagesize)
      .countSelect();

    return this.json(list);
  }

  // 获取收款账户
  async getaccountlistAction() {
    const filter = JSON.parse(this.post('filter'));
    const where = {
      departmentid: this.shop_userinfo.departmentid,
      isdisable: 0
    };
    if (filter.keywords) where['name|number'] = ['like', '%' + filter.keywords + '%'];

    const list = await this.model('or_shop_account').where(where).page(filter.currentpage, filter.pagesize).select();
    const count = await this.model('or_shop_account').where(where).count();
    const data = {
      list: list,
      count: count
    };
    return this.json(data);
  }

  // 获取分店的员工列表
  async getappuserAction() {
    const filter = JSON.parse(this.post('filter'));
    const guestid = this.post('gid');
    let allot = [];
    const shopid = this.shop_userinfo.departmentid;
    if (guestid) {
      allot = await this.model('or_allotuser')
        .alias('a')
        .join('`think_or_app_user` u on u.id=a.uid')
        .where({'a.gid': guestid})
        .getField('a.uid');
    }
    const where = {
      'u.shopid': shopid,
      'u.isdisable': 0,
      'u.isdelete': 0
    };
    if (filter.keywords) where['u.name|u.worknum'] = ['like', '%' + filter.keywords + '%'];
    if (filter.ismanage) where['u.ismanage'] = filter.ismanage;
    let list;
    if (filter.pagesize) {
      list = await this.model('or_app_user')
        .alias('u')
        .field('if(p.name!="",p.name,"暂无") as zcname, u.*')
        .join('`think_or_position` p on p.id=u.zhichengid')
        .where(where)
        .page(filter.currentpage, filter.pagesize)
        .select();
    } else {
      list = await this.model('or_app_user')
        .alias('u')
        .field('if(p.name!="",p.name,"暂无") as zcname, u.*')
        .join('`think_or_position` p on p.id=u.zhichengid')
        .where(where)
        .select();
    }
    const count = await this.model('or_app_user').alias('u').where(where).count();
    const data = {
      aid: allot,
      list: list,
      count: count
    };
    return this.json(data);
  }

  // 获取有卡的客户列表
  async getcardguestsAction() {
    const page = JSON.parse(this.post('page'));
    const pages = page.pages;
    const limits = page.limits;
    const search = page.search;
    const shopid = this.shop_userinfo.departmentid;

    const list = await this.model('or_guest')
      .alias('g')
      .field('g.*')
      .join('think_or_shop_guestcard gc on gc.guestid = g.id')
      .where({'gc.departmentid': shopid, 'g.name|g.phone|g.vipcard': ['like', '%' + search + '%'], 'g.isdisable': 0, 'gc.status': 1, 'g.initial_info': 1})
      .page(pages, limits)
      .order('g.id DESC')
      .group('g.id')
      .select();
    const data = {
      list: list,
      count: list.length
    };
    return this.json(data);
  }

  // 获取卡的项目
  async getcardsubjectlistAction() {
    const id = this.post('id');
  }

  async categorylistAction() {
    const departmentid = await this.model('or_department').where({id: this.shop_userinfo.departmentid}).getField('pid', true);
    const plist = await this.model().query('SELECT * FROM think_or_subjectcategory WHERE departmentid=' + departmentid + ' AND pid=0');
    const clist = await this.model().query('SELECT * FROM think_or_subjectcategory WHERE departmentid=' + departmentid + ' AND pid!=0');
    const data = {
      p: plist,
      c: clist
    };
    return this.json(data);
  }

  async searchFeatTypeAction() {
    const filter = this.get();
    const where = {};
    where['s.type'] = filter.type;
    where['s.departmentid'] = this.shop_userinfo.departmentid;
    where['s.subjectid'] = filter.id;
    const list = await this.model('or_subject_config').alias('s').join('think_or_subject_childclass c on s.subjectchildclassid = c.id').where(where).select();
    return this.json(list);
  }
}
